import { defineStore } from "pinia";
import { PositionInfo, RouteLineType } from "@/utils/type";
import marker from "./marker";
import map from "./map";
import poi from "./poi";
import { closeToast, showToast } from "vant";
import { routeInputObj } from "@/components/routeInput/RouteInput";
import { pathObj } from "@/components/path/Path";
import control from "@/utils/control";
import navImg from "@/assets/img/nav/nav.png";
import startImg from "@/assets/img/nav/start.png";
import endImg from "@/assets/img/nav/end.png";
import { navObj } from "@/components/nav/Nav";
import { detailsObj } from "@/components/details/Details";
import { navi } from "..";
import {
  realNaviStart,
  realNaviStop,
  resetWalkNaviPoints,
  walkNaviPoints,
} from "@/utils/record";
import { fmapObj } from "@/components/fmap/Fmap";

// 注：导航器不能为proxy
let simulatedNavigator: any = null; //模拟导航器
let locationNavigator: any = null; //定位导航器
let recordNavigator: any = null; //重新记录的定位导航器

const useNaviStore = defineStore("navigator", {
  state: () => ({
    status: false, //导航过程状态
    coord: {
      x: 0,
      y: 0,
      level: 0,
      buildingID: 0,
    }, //导航过程中的点
    lastPoiTime: 0,
    // defaultPosition: {
    //   x: 13530046.987808883,
    //   y: 3661606.1223999485,
    //   floorId: 2,
    //   level: 2,
    // } as PositionInfo, //上图正门坐标
    // defaultName: "正门",
    //-----------------------------------------------------------------
    defaultName: "儿童文学时空馆",
    defaultPosition: {
      x: 13529444.688489787,
      y: 3658003.232810858,
      floorId: 3,
      level: 3,
    } as PositionInfo, //正门坐标
    curPosition: {
      x: 0,
      y: 0,
      floorId: 0,
      level: 0,
    } as PositionInfo, //当前位置
    firstCenterFlag: true, //是否第一次初始化中心点
    localPositionFlag: false, //是否开启定位
    moveLocationFlag: true, //是否更新当前位置, true 更新当前位置，false 不更新当前位置
    route1: {} as RouteLineType, //智能推荐
    route2: {} as RouteLineType, //直梯优先
    route3: {} as RouteLineType, //扶梯优先
    routeList: [] as RouteLineType[],
    startTime: 0,
    lastResetNaviRouteTime: 0,
    locationTimer: undefined as any, //定位计时器
    currentWayIndex: -1, //当前路段的索引
  }),
  getters: {},
  actions: {
    moveLocationCenter(time?) {
      // 非导航状态下更新当前坐标
      if (!this.status && this.moveLocationFlag) {
        setTimeout(
          () => {
            console.log("更新当前坐标", this.curPosition);
            marker.setLocationMarker(this.curPosition);
            marker.moveLocationMarker(this.curPosition);
          },
          time ? time : 800
        );
      }
    },
    verifyRoutePois() {
      console.log("当前点：", poi.now);
      console.log("开始点：", poi.start);
      console.log("结束点：", poi.end);
      // 导航准备，检验起点终点是否合格
      if (JSON.stringify(poi.start) == "{}") {
        showToast("起点有误，请稍后再试");
        return;
      }
      if (JSON.stringify(poi.end) == "{}") {
        showToast("终点有误，请稍后再试");
        return;
      }
      if (poi.start.fid == poi.end.fid) {
        alert("起点和终点不能相同！请重新选择");
        return;
      }

      //更新页面和poi信息状态
      map.curPageType = "path";
      poi.infoType = "";

      // 打开导航,路径组件
      map.routeInputFlag = true;
      map.pathFlag = true;
      routeInputObj.origin = "details";

      //重新画起点和终点
      marker.removeImageMarker();
      marker.setStart();
      marker.setEnd();

      //显示模拟导航还是真实导航
      if (navi.curPosition.x != 0 && navi.curPosition.y != 0) {
        pathObj.navType = "实时";
      } else {
        pathObj.navType = "模拟";
      }

      //是否显示智能选择
      pathObj.endFloorIdx = poi.end.floorId;
      if (poi.start.floorId == poi.end.floorId) {
        // 显示当前层路线
        pathObj.routeWrapFlag = false;
      } else {
        //显示所有路线，顶部导航路线弹框指引
        pathObj.routeWrapFlag = true;
      }
      return true;
    },
    initRouteList() {
      if (poi.start.floorId !== poi.end.floorId) {
        // 起点终点不同楼层
        this.route1 = {
          type: "best",
          name: "智能推荐",
          // @ts-ignore
          mode: fengmap.FMNaviMode.MODULE_BEST,
          // @ts-ignore
          priority: fengmap.FMNaviPriority.PRIORITY_DEFAULT,
          route: {},
          time: 0,
        };
        this.route2 = {
          type: "leftFirst",
          name: "直梯优先",
          // @ts-ignore
          mode: fengmap.FMNaviMode.MODULE_SHORTEST,
          // @ts-ignore
          priority: fengmap.FMNaviPriority.PRIORITY_LIFTONLY,
          route: {},
          time: 0,
        };
        this.route3 = {
          type: "escalatorFirst",
          name: "扶梯优先",
          // @ts-ignore
          mode: fengmap.FMNaviMode.MODULE_SHORTEST,
          // @ts-ignore
          priority: fengmap.FMNaviPriority.PRIORITY_ESCALATORONLY,
          route: {},
          time: 0,
        };
        this.routeList = [this.route1, this.route2, this.route3];
      } else {
        // 起点终点同楼层
        this.route1 = {
          type: "best",
          name: "智能推荐",
          // @ts-ignore
          mode: fengmap.FMNaviMode.MODULE_BEST,
          // @ts-ignore
          priority: fengmap.FMNaviPriority.PRIORITY_DEFAULT,
          route: {},
          time: 0,
        };
        this.routeList = [this.route1];
      }
    },
    async startRoute() {
      console.log("规划路线");
      control.removeControls();
      this.startTime = new Date().getTime() / 1000;
      this.initRouteList();
      let promises = [] as any[];
      let isRouteSuccess = false;
      this.routeList.forEach((item) => {
        console.log(item);
        let timer = setInterval(() => {
          if (isRouteSuccess) {
            clearInterval(timer);
          } else {
            map.routeFailedDialog = true;
            isRouteSuccess = true;
          }
        }, 3000);

        const routeOpiton = {
          start: {
            level: poi.start.floorId,
            x: poi.start.coordinateX,
            y: poi.start.coordinateY,
          },
          dest: {
            level: poi.end.floorId,
            x: poi.end.coordinateX,
            y: poi.end.coordinateY,
          },
          mode: item.mode,
          priority: item.priority,
          toDoors: true, //到门口停止导航
        };

        const getRouteInfo = new Promise((resolve, reject) => {
          map.analyser?.route(
            routeOpiton,
            (result) => {
              console.log("规划路线成功", result);
              isRouteSuccess = true;
              // closeToast();
              detailsObj.isLoading = false;
              map.routeFailedDialog = false;
              resolve({
                ...item,
                route: result,
                time: new Date().getTime() / 1000 - this.startTime,
              });
            },
            (error) => {
              map.routeFailedDialog = true;
              console.error("路线规划失败：", error);
              reject(error);
            }
          );
        });
        promises.push(getRouteInfo);
      });
      this.routeList = await Promise.all(promises);
      console.log("路线信息", this.routeList);
      map.routeFlag = false;

      // TODO:aoa?
      // if (map.aoaRecommend) {
      //   this.startNavigation(this.routeList[0]);
      //   map.menuFlag = false;
      //   map.navFlag = true;
      //   map.setZoom(22);
      //   // aoa数据更新到poi.now
      //   return;
      // }

      // 绘制路线
      setTimeout(() => {
        this.routeList.forEach((item, index) => {
          if (!pathObj.routeWrapFlag) {
            //显示当前楼层
            this.addNaviLine(item);
          } else {
            //所有楼层，渲染多条路线数据
            pathObj.routeData[index] = {
              // TODO:图片路径this.$cosUrl
              imageUrl: `https://map-1306178125.cos.ap-shanghai.myqcloud.com/images/path/assets/img/route${
                index + 1
              }.png`,
              title: item.name,
              distance: item.route.distance.toFixed(2),
              minute: item.time.toFixed(2),
            };
            if (pathObj.routeIdx == index) {
              this.addNaviLine(this.routeList[pathObj.routeIdx]);
            }
          }
        });

        if (map.curPageType == "path") {
          map.menuFlag = false;
          map.searchFlag = false;
          map.detailsFlag = false;
          map.routeInputFlag = true;
          map.pathFlag = true;
          pathObj.routeIdx = 0; //默认展示智能推荐
        }
      }, 200);
    },
    addNaviLine(routeLine: RouteLineType) {
      //地图上绘制路线
      this.resetNavigation();
      const naviRequest = {
        start: {
          level: poi.start.floorId,
          x: poi.start.coordinateX,
          y: poi.start.coordinateY,
        },
        end: {
          level: poi.end.floorId,
          x: poi.end.coordinateX,
          y: poi.end.coordinateY,
        },
        mode: routeLine.mode,
        priority: routeLine.priority,
        toDoors: true,
      };
      map.analyserNavigation.setStartPoint(naviRequest.start);
      map.analyserNavigation.setDestPoint(naviRequest.end);
      map.analyserNavigation.route(
        naviRequest,
        (result: any) => {
          map.analyserNavigation.drawNaviLine();
          console.log("绘制路线成功");
        },
        (error: any) => {
          console.error("绘制路线失败：", error);
        }
      );
    },
    resetNavigation() {
      map.setZoom(20);
      marker.removeImageMarker();
      map.compassUpdate = false;
      this.status = false;
      clearInterval(this.locationTimer);
      map.analyserNavigation.clearNaviLine();

      if (locationNavigator != null) {
        locationNavigator.clearLocationMarker();
        locationNavigator.clearNaviLine();
        locationNavigator.clearAll();
        locationNavigator.dispose();
        locationNavigator = null;
      }
      if (simulatedNavigator != null) {
        simulatedNavigator.clearNaviLine();
        simulatedNavigator.clearAll();
        simulatedNavigator.dispose();
        simulatedNavigator = null;
      }
      if (recordNavigator != null) {
        recordNavigator.clearNaviLine();
        recordNavigator.clearAll();
        recordNavigator.dispose();
        recordNavigator = null;
      }
    },
    startRecord(routeLine: RouteLineType) {
      this.moveLocationFlag = true;
      this.status = true;
      this.resetNavigation();
      // 添加定位点marker
      let start = {
        x: walkNaviPoints[0].x,
        y: walkNaviPoints[0].y,
        floorId: walkNaviPoints[0].level,
        level: walkNaviPoints[0].level,
      } as PositionInfo;
      marker.setLocationMarker(start);
      const naviRequest = {
        start: {
          level: poi.start.floorId,
          x: poi.start.coordinateX,
          y: poi.start.coordinateY,
          url: startImg,
          // @ts-ignore
          anchor: fengmap.FMMarkerAnchor.BOTTOM,
          size: 22,
        },
        end: {
          level: poi.end.floorId,
          x: poi.end.coordinateX,
          y: poi.end.coordinateY,
          url: endImg,
          // @ts-ignore
          anchor: fengmap.FMMarkerAnchor.BOTTOM,
          size: 22,
        },
        mode: routeLine.mode,
        priority:
          poi.start.floorId === 4
            ? // @ts-ignore
              fengmap.FMNaviPriority.PRIORITY_LIFTONLY
            : routeLine.priority,
        toDoors: true,
      };
      let that = this;
      // @ts-ignore
      let analyser = new fengmap.FMNaviWalkAnalyser(
        { map: map.fmap },
        () => {
          // @ts-ignore
          recordNavigator = new fengmap.FMNavigationWalk({
            map: map.fmap,
            followPosition: true,
            analyser: analyser,
            locationMarkerUrl: navImg,
            locationMarkerSize: 32,
            linePassed: true,
          });
          // 设置起终点
          recordNavigator.setStartPoint(naviRequest.start);
          recordNavigator.setDestPoint(naviRequest.end);

          // 导航分析
          recordNavigator.route(
            naviRequest,
            (result: any) => {
              // 导航分析成功回调
              recordNavigator.drawNaviLine();
              console.log("重现导航路线绘制成功");
              // 自适应路线全览,系统自带模拟导航不能暂停
              realNaviStart(walkNaviPoints, function (point) {
                if (point) {
                  // 全路网路径约束
                  analyser.pathConstraint({
                    x: point.x,
                    y: point.y,
                    level: point.level,
                  });
                  recordNavigator.locate(point);
                } else {
                  that.stopNavigation();
                }
              });
            },
            (error: any) => {
              console.error("绘制路线失败：", error);
            }
          );

          recordNavigator.on("walking", (info: any) => {
            console.log("重现导航过程中", info);
            // @ts-ignore
            map.fmap.setViewMode({ mode: fengmap.FMViewMode.MODE_2D });
            closeToast();
            map.routeInputFlag = false;
            map.pathFlag = false;
            map.navFlag = true;

            // 导航过程中的回调函数
            if (info.index < 0) return;
            let zhMsg =
              recordNavigator.naviResult.subs[info.index].instruction.zh;
            if (this.currentWayIndex == -1) this.currentWayIndex = info.index;
            if (this.currentWayIndex !== info.index) {
              //更换路段
              this.playVoice(zhMsg);
              this.currentWayIndex = info.index;
              map.setMapCenter({ ...info.point, floorId: info.point.level });
            }

            //更新导航指引信息
            navObj.remain = info.remain.toFixed(0);
            navObj.title = zhMsg;

            //更新定位图标的位置及旋转角度
            if (this.moveLocationFlag) {
              this.coord = info.point;
              marker.updateLocationMakerPosition(this.coord, info.angle);
            }
            //当剩余距离小于设置的距离终点的最小距离时，自动结束导航
            //偏航处理
            // console.log("偏移距离：", info.distance);
            if (info.distance > 7) {
              // 结束导航
              realNaviStop();
              // 重新绘制导航线
              this.resetNaviRoute(recordNavigator, info.point);
            }

            if (info.remain <= 2) {
              this.stopNavigation();
            }
          });
        },
        (error: any) => {}
      );
    },
    startNavigation(routeLine: RouteLineType) {
      this.moveLocationFlag = true;
      this.status = true;
      this.resetNavigation();
      marker.setLocationMarker(this.curPosition); //用来设置当前位置标记，使地图视角中心移动到当前位置
      const naviRequest = {
        start: {
          level: poi.start.floorId,
          x: poi.start.coordinateX,
          y: poi.start.coordinateY,
        },
        end: {
          level: poi.end.floorId,
          x: poi.end.coordinateX,
          y: poi.end.coordinateY,
        },
        mode: routeLine.mode,
        priority:
          poi.start.floorId === 4
            ? // @ts-ignore
              fengmap.FMNaviPriority.PRIORITY_LIFTONLY
            : routeLine.priority,
        toDoors: true,
      };
      // @ts-ignore
      let analyser = new fengmap.FMNaviAnalyser(
        { map: map.fmap },
        () => {
          // @ts-ignore
          locationNavigator = new fengmap.FMNavigation({
            map: map.fmap,
            followPosition: true,
            analyser: analyser,
            locationMarkerUrl: navImg,
            locationMarkerSize: 32,
            linePassed: true,
          });
          locationNavigator.setStartPoint(naviRequest.start);
          locationNavigator.setDestPoint(naviRequest.end);
          // 全路网路径约束,吸附定位点到路线上
          analyser.pathConstraint({
            x: this.curPosition.x,
            y: this.curPosition.y,
            level: this.curPosition.level,
          });
          locationNavigator.route(
            naviRequest,
            (result: any) => {
              locationNavigator.clearNaviLine();
              locationNavigator.drawNaviLine();
              console.log("实时导航路线绘制成功");
              //真实导航定时器
              this.locationTimer = setInterval(() => {
                locationNavigator.locate(this.curPosition);
              }, 800);
            },
            (error: any) => {
              console.error("绘制路线失败：", error);
            }
          );
          locationNavigator.on("walking", (info: any) => {
            console.log("实时导航过程中", info);
            closeToast();
            map.routeInputFlag = false;
            map.pathFlag = false;
            map.navFlag = true;

            // 导航过程中的回调函数
            if (info.index < 0) return;
            let zhMsg =
              locationNavigator.naviResult.subs[info.index].instruction.zh;
            if (this.currentWayIndex == -1) this.currentWayIndex = info.index;
            if (this.currentWayIndex !== info.index) {
              //更换路段
              this.playVoice(zhMsg);
              this.currentWayIndex = info.index;
            }

            //更新导航指引信息
            navObj.remain = info.remain.toFixed(0);
            navObj.title = zhMsg;

            //TODO:aoa?
            if (map.isInAoA) {
              if (info.remain <= 2) {
                // aoaRef.value.setEnd()
              }
            } else {
              if (info.remain <= 2) {
                this.stopNavigation();
              }
            }
            //更新定位图标的位置及旋转角度
            if (this.moveLocationFlag) {
              this.coord = info.point;
              marker.updateLocationMakerPosition(this.coord, info.angle);
            }
            //当剩余距离小于设置的距离终点的最小距离时，自动结束导航
            //偏航处理
            if (info.distance > 7) {
              // 停止位置更新
              clearInterval(this.locationTimer);
              // 重新绘制导航线
              this.resetNaviRoute(locationNavigator, info.point);
            }
          });
        },
        (error: any) => {}
      );
    },
    startSimulate(routeLine: RouteLineType) {
      this.resetNavigation();
      this.status = true;
      const routeOpiton = {
        start: {
          level: poi.start.floorId,
          x: poi.start.coordinateX,
          y: poi.start.coordinateY,
          url: startImg,
          // @ts-ignore
          anchor: fengmap.FMMarkerAnchor.BOTTOM,
          size: 22,
        },
        end: {
          level: poi.end.floorId,
          x: poi.end.coordinateX,
          y: poi.end.coordinateY,
          url: endImg,
          // @ts-ignore
          anchor: fengmap.FMMarkerAnchor.BOTTOM,
          size: 22,
        },
        mode: routeLine.mode,
        priority:
          poi.start.floorId === 4
            ? // @ts-ignore
              fengmap.FMNaviPriority.PRIORITY_LIFTONLY
            : routeLine.priority,
        toDoors: true,
      };

      //模拟导航参数
      let subjunctive = {
        speed: 10,
        followPosition: true,
        followAngle: true,
        changeTiltAngle: true,
        zoom: 20,
        maxZoom: 20,
      };

      // @ts-ignore
      let analyser = new fengmap.FMNaviAnalyser(
        map.mapOptions,
        () => {
          // @ts-ignore
          simulatedNavigator = new fengmap.FMNavigation({
            map: map.fmap,
            analyser: analyser,
            locationMarkerUrl: navImg,
            locationMarkerSize: 32,
          });
          console.log("routeOpiton.start", routeOpiton.start);
          console.log("routeOpiton.end", routeOpiton.end);

          simulatedNavigator.setStartPoint(routeOpiton.start);
          simulatedNavigator.setDestPoint(routeOpiton.end);
          simulatedNavigator.route(
            routeOpiton,
            (result: any) => {
              let that = this;
              simulatedNavigator.clearNaviLine();
              simulatedNavigator.drawNaviLine();
              // 自适应路线全览,系统自带模拟导航不能暂停
              simulatedNavigator.overview({ ratio: 1.5 }, () => {
                setTimeout(function () {
                  simulatedNavigator.simulate(subjunctive);
                }, 800);
              });

              //自定义模拟导航,不能确定剩余距离，指引信息和路段点对应
              // setInterval(()=>{
              // if(!navObj.abortFlag){
              // closeToast();
              // map.routeInputFlag = false;
              // map.pathFlag = false;
              // map.navFlag = true;
              // }
              // },1000)
              // simulatedNavigator.naviResult.subs.forEach(item=>{
              //   console.log(item.instruction.zh,item.waypoint.points);
              //   let zhMsg =item.instruction.zh;
              // })
            },
            (error: any) => {
              console.error(error);
            }
          );
          simulatedNavigator.setSpeed(1);
          // console.log('导航速度',simulatedNavigator.getSpeed());

          simulatedNavigator.on("walking", (info: any) => {
            // console.log("模拟导航过程中", info);
            closeToast();
            map.routeInputFlag = false;
            map.pathFlag = false;
            map.navFlag = true;

            // 导航过程中的回调函数
            if (info.index < 0) return;
            let zhMsg =
              simulatedNavigator.naviResult.subs[info.index].instruction.zh; //更新导航指引信息
            if (this.currentWayIndex == -1) this.currentWayIndex = info.index;
            if (this.currentWayIndex !== info.index) {
              //更换路段
              this.playVoice(zhMsg);
              this.currentWayIndex = info.index;
            }
            navObj.remain = info.remain.toFixed(0);
            // this.playVoice("开始模拟导航");
            navObj.title = zhMsg;
            if (info.remain <= 1) {
              this.stopNavigation();
            }
          });

          simulatedNavigator.on("complete", (info) => {
            navObj.abortFlag = false;
          });
        },
        (error: any) => {
          console.log(error);
        }
      );
    },
    playVoice(msg) {
      console.log("语音播报", msg);

      if (msg === "") {
        msg = "目的地已到达，导航结束";
      }
      map.voiceSrc = map.voiceBaseSrc + encodeURIComponent(msg);

      const audio: any = document.getElementById("mp3Btn");
      if (audio) {
        audio.load();
        setTimeout(() => {
          // @ts-ignore
          if (window.WeixinJSBridge) {
            // @ts-ignore
            WeixinJSBridge.invoke(
              "getNetworkType",
              {},
              function (e) {
                audio.play();
              },
              false
            );
          } else {
            document.addEventListener(
              "WeixinJSBridgeReady",
              function () {
                // @ts-ignore
                WeixinJSBridge.invoke("getNetworkType", {}, function (e) {
                  audio.play();
                });
              },
              false
            );
          }
          audio.play();
        }, 500);
      }
    },
    resetNaviRoute(navigator, point) {
      // 处理偏航
      if (!(new Date().getTime() - this.lastResetNaviRouteTime < 30000)) {
        this.lastResetNaviRouteTime = new Date().getTime();
        let msg = "你已偏航，路线重新规划中";
        showToast(msg);
        this.playVoice(msg);
      }

      console.log("你已偏航，路线重新规划中");
      console.log("当前位置：", this.curPosition);
      console.log("终点：", poi.end);

      if (fmapObj.isRecord) {
        navigator.setStartPoint({
          x: resetWalkNaviPoints[0].x,
          y: resetWalkNaviPoints[0].y,
          level: resetWalkNaviPoints[0].level,
          height: 3,
          url: startImg,
          size: 22,
        });
      } else {
        // 更新起点坐标
        navigator.setStartPoint({
          x: this.curPosition.x,
          y: this.curPosition.y,
          level: this.curPosition.level,
          height: 3,
          url: startImg,
          size: 22,
        });
      }
      navigator.route(
        {
          // @ts-ignore
          mode: fengmap.FMNaviMode.MODULE_SHORTEST, // 扶梯
          // @ts-ignore
          priority: fengmap.FMNaviPriority.PRIORITY_DEFAULT, // 智能推荐
        },
        (result: any) => {
          console.log("reset nav success", result);
          navigator.clearNaviLine();
          navigator.drawNaviLine();

          if (fmapObj.isRecord) {
            //重新开始导航
            realNaviStart(resetWalkNaviPoints, function (point) {
              if (point) {
                navigator.locate(point);
              }
            });
          } else {
            //重新开始导航
            this.locationTimer = setInterval(() => {
              navigator.locate(this.curPosition);
            }, 800);
          }
        },
        (result: any) => {
          console.error("reset nav failed", result);
        }
      );
    },
    stopNavigation() {
      console.log("停止导航");
      navObj.remain = 0;
      navObj.maskFlag = true;
      navObj.endFlag = true;
      this.currentWayIndex = -1;
      this.playVoice("");
      map.websocketObj.closeWebSocket();
      this.resetNavigation();
      if (fmapObj.isRecord) realNaviStop();
      // control.addCompassControl();
    },
  },
});

export default useNaviStore();
